import {handleActions} from 'redux-actions';

import { STUDENT_PROFILE, PROFILE_UPDATE, STUDENTS_QUERY, STUDENTS_DELETE, STUDENTS_DELETE_NOTIFY } from '../actions/ActionTypes.js'

const student = handleActions({
  [STUDENT_PROFILE.REQUEST](state) {
    return {...state, loading: true,};
  },
  [STUDENT_PROFILE.SUCCESS](state, action) {
    return {...state, ... action.payload, loading: false,};
  },
  [STUDENT_PROFILE.FAILURE](state, action) {
    return {...state, err: action.err, loading: false,};
  },
  [PROFILE_UPDATE](state, action) {
    return {...state, ... action.payload, loading: false,};
  },
  [STUDENTS_QUERY.REQUEST](state, action) {
    const pagination = {...state.students.pagination, pageSize:action.payload.pageSize, current:action.payload.current };
    const students = {...state.students, pagination };
    const result = {...state, students:students, loading: true,};
    return result;
  },
  [STUDENTS_QUERY.SUCCESS](state, action) {
    const pager = {...state.students.pagination, total:action.payload.total };
    const students = {...state.students, data:action.payload.data, pagination: pager};
    const result = {...state, students, loading: false,};
    return result;
  },
  [STUDENTS_QUERY.FAILURE](state, action) {
    return {...state, err: action.err, loading: false,};
  },
  [STUDENTS_DELETE.REQUEST](state, action) {
    return {...state, loading:true};
  },
  [STUDENTS_DELETE.SUCCESS](state, action) {
    return {...state, loading:false};
  },
  [STUDENTS_DELETE.FAILURE](state, action) {
    return {...state, err: action.err, loading: false,};
  },
  [STUDENTS_DELETE_NOTIFY](state, action) {
    console.log('STUDENTS_DELETE_NOTIFY,action=', action);
    console.log('STUDENTS_DELETE_NOTIFY,students=', state.students.data);

    const data = state.students.data.filter((student) => {
      return action.payload.ids.findIndex((id, index, ids) => {return (id == student.id)}) < 0;
    });
    console.log("STUDENTS_DELETE_NOTIFY.data=", data);
    const students = {...state.students, data };
    return {...state, students, loading: false,};
  },
}, {
  loading:false,
  err:{},
  students:{
    data:[],
    pagination:{
      pageSize:10,
      current:1,
      total:0,
    },

  }
});

export default student;
